package zsche;

import java.io.File;
import java.sql.SQLException;
import java.util.List;
import java.util.Random;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.StringUtils;

import wemai.WebMail;

import comm.DbUtils;

public class XqMain {
	List<Acc> accs = null;
	QueryRunner qr = null;
	String gid = null;
	List<String> xhs = null;
	int accsIndex = 0;
	String rawcontent = null;

	public XqMain(String gid) throws Exception {
		this.gid = gid;
		qr = DbUtils.getQueryRunner();
		String sql = " select id,at,pp from ACC where work=1   order by dbms_random.value() ";
		accs = qr.query(sql, new BeanListHandler<Acc>(Acc.class));

		xhs = FileUtils.readLines(new File("c:\\csuu\\xh.txt"), "utf-8");

		
		rawcontent = FileUtils.readFileToString(new File("c:\\csuu\\cont.txt"), "utf-8");

	}

	public List<String> getGods(int num) throws SQLException {
		String sql = "select id as id  from god  where gid = ? and msg is null  and rownum <= ? ";
		List<String> gods = qr.query(sql, new ColumnListHandler<String>("id"), gid, num);
		return gods;
	}

	public void updateGods(List<String> gods, String msg) throws SQLException {
		String sql = "update god set msg = ? where gid=? and id in  (" + DbUtils.inString(gods) + ")  ";
		qr.update(sql, msg, this.gid);
	}

	public void run() {
		while (true) {
			try {
				List<String> tos = this.getGods(5);
				if (tos.size() == 0) {
					System.out.println("done!");
					break;
				}
				send(tos);
				updateGods(tos, "1");
				sheep(5000);
			} catch (Exception e) {
				sheep(10000);
				e.printStackTrace();
			}
		}
	}

	private void send(List<String> gods) throws Exception {

		Acc acc = accs.get(accsIndex++ % accs.size());
		String to = StringUtils.join(gods, "@qq.com;") + "@qq.com";

		String className = "wemai.m_" + acc.at.replace(".", "");
		WebMail wm = (WebMail) Class.forName(className).newInstance();

		String xh = xhs.get(   RandomUtils.nextInt(xhs.size())  );

		String title = xh.substring(0, 10);

		String content = rawcontent + "<font face=\"幼圆\" size=\"5\">" + xh + "</font>";

		wm.send(acc.getId(), acc.getPp(), to, title, content);

		String url = this.gid + ")" + acc.getId() + "," + acc.getAt() + "->" + StringUtils.join(gods, ";");
		System.out.println(url);

	}

	private void sheep(int millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws Exception {
		XqMain xqm = new XqMain("jf");
		xqm.run();

	}

}
